package com.cn.lp.openapi.aop;

import com.cn.lp.common.utils.BlankAide;
import com.cn.lp.openapi.base.OpenApiClientConstants;
import feign.Client;
import feign.Request;
import feign.Response;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.core.env.Environment;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

public class FeignClientProxy implements Client {

    private LoadBalancerFeignClient target;

    private Environment environment;

    public FeignClientProxy(LoadBalancerFeignClient target, Environment environment) {
        this.target = target;
        this.environment = environment;
    }

    public Client getDelegate() {
        return this.target;
    }

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        Map<String, Collection<String>> headers = request.headers();
        if(BlankAide.isNotBlank(headers)) {
            Collection<String> dynUrlKeys = headers.get(OpenApiClientConstants.DYN_URL);
            if (BlankAide.isNotBlank(dynUrlKeys)) {
                String dynUrlKey = dynUrlKeys.stream().findFirst().get();
                String dynUrl = environment.getProperty(dynUrlKey);
                if(BlankAide.isNotBlank(dynUrl)) {
                    return target.getDelegate().execute(request, options);
                }
            }
            Collection<String> dynNameKeys = headers.get(OpenApiClientConstants.DYN_NAME);
            if (BlankAide.isNotBlank(dynNameKeys)) {
                String dynNameKey = dynNameKeys.stream().findFirst().get();
                String dynName = environment.getProperty(dynNameKey);
                if(BlankAide.isNotBlank(dynName)) {
                    return target.execute(request, options);
                }
            }
        }
        return target.getDelegate().execute(request, options);
    }
}
